package cn.netswap.crate.autoconfigure;


import cn.netswap.crate.datasource.CrateHikariDataSource;
import cn.netswap.crate.handler.CrateDbAutoCrateTableHandler;
import com.zaxxer.hikari.HikariConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 *
 */
@Configuration
@EnableConfigurationProperties(CrateProperties.class)
@ConditionalOnProperty(prefix = "crate", name = "open", havingValue = "true")
public class AutomaticAssemblyCrateDbConfig {

    @Autowired
    CrateProperties crateProperties;

    @Bean
    public CrateDbAutoCrateTableHandler crateDbAutoCrateTableHandler() {
        return new CrateDbAutoCrateTableHandler();
    }

    @Bean
    public CrateHikariDataSource crateHikariDataSource(){
        return new CrateHikariDataSource();
    }

    @Bean
    public HikariConfig hikariConfig(){
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(crateProperties.getHikari().getJdbcUrl());
        hikariConfig.setUsername(crateProperties.getHikari().getUsername());
        hikariConfig.setPassword(crateProperties.getHikari().getPassword());
        hikariConfig.setPoolName(crateProperties.getHikari().getPoolName());
        hikariConfig.setMaximumPoolSize(Integer.parseInt(crateProperties.getHikari().getMaximumPoolSize()));
        hikariConfig.setMinimumIdle(Integer.parseInt(crateProperties.getHikari().getMinimumIdle()));
        hikariConfig.setConnectionTimeout(Integer.parseInt(crateProperties.getHikari().getConnectionTimeout()));
        hikariConfig.setDriverClassName(crateProperties.getHikari().getDriverClassName());
        return hikariConfig;
    }
}